#! /usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Created by jianbing on 2017-09-13
"""
import collections
import functools
import json


class CallHelper:
    model = collections.defaultdict(set)  # 存放每个类需要被调用的函数
    instance = {}

    @classmethod
    def sign(cls, target):
        cls.instance[target] = {}
        cls.instance[target]['require_call'] = cls.model.get(str(target.__class__).split(".")[-1][:-2]).copy()
        cls.instance[target]['max_call'] = {}

    @classmethod
    def check_require_call(cls, target):
        if cls.instance[target]['require_call']:
            for i in cls.instance[target]['require_call']:
                print("需要调用{}的{}方法，添加图表数据".format(str(target), i))
            raise Exception("根据上边的提示修改代码")

    @classmethod
    def update_model(cls, func):
        class_name, method_name = func.__qualname__.split(".")
        cls.model[class_name].add(method_name)

    @classmethod
    def record_call(cls, target, func, max_time):
        if func.__name__ in cls.instance[target]['require_call']:
            cls.instance[target]['require_call'].remove(func.__name__)

        func_name = func.__name__
        if func_name not in cls.instance[target]['max_call']:
            cls.instance[target]['max_call'][func_name] = max_time - 1
        else:
            if cls.instance[target]['max_call'][func_name] <= 0:
                raise Exception("{}函数限制调用次数，最多为{}次".format(func_name, max_time))
            else:
                cls.instance[target]['max_call'][func_name] -= 1


def register(max_time=1000, need_call=True):
    def _wrap(func):
        # 统计需要调用的方法
        if need_call:
            CallHelper.update_model(func)

        @functools.wraps(func)
        def __wrap(*args, **kwargs):
            CallHelper.record_call(args[0], func, max_time)
            return func(*args, **kwargs)

        return __wrap

    return _wrap


def dumps_option(op):
    return json.dumps(op, ensure_ascii=False, indent=4)
